package com.sx.mvvmlibs.http.tools.encrypts;

import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.sx.mvvmlibs.http.impl.IBaseResponse;
import com.sx.mvvmlibs.http.tools.EncryptionDecryptUtils;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * @Author: YY
 * @Date: 2021/4/8
 * @Description: 响应解密转换器
 */
public class EncryptResponseConverter <T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final Type type;
    private final String serverPubKey;

    public EncryptResponseConverter(Gson gson, Type type, String serverPubKey) {
        this.gson = gson;
        this.type = type;
        this.serverPubKey = serverPubKey;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        JsonReader jsonReader = gson.newJsonReader(value.charStream());
        try {
            TypeAdapter<IBaseResponse<Map<String, String>>> adapter
                    = gson.getAdapter(new TypeToken<IBaseResponse<Map<String, String>>>(){});
            IBaseResponse<Map<String, String>> result = adapter.read(jsonReader);
            if (jsonReader.peek() != JsonToken.END_DOCUMENT) {
                throw new JsonIOException("JSON document was not fully consumed.");
            }
            Map<String, String> encryptData = result.data();
            String aesKey = encryptData.get("aesKey");
            String data = encryptData.get("data");

            String decryptedJson = EncryptionDecryptUtils.decrypt(aesKey, data, serverPubKey);
            return gson.fromJson(decryptedJson, type);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            value.close();
        }
    }
}
